package com.ldu.exam.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ldu.exam.dao.AccountRepository;
import com.ldu.exam.dao.SubmitPaperRepository;
import com.ldu.exam.dao.SubmitQuestionRepository;
import com.ldu.exam.model.AccountModel;
import com.ldu.exam.model.SubmitPaper;
import com.ldu.exam.model.SubmitQuestion;

@Service
public class MarkPaperService 
{
	@Autowired SubmitPaperRepository submitPaperRepository;
	@Autowired SubmitQuestionRepository submitQuestionRepository;
	@Autowired AccountRepository accountRepository;
	
	public Object markPaper(Set<SubmitQuestion> set)
	{
		int score = 0;
		String paperId = "";
		Set<SubmitQuestion> setForIn = new HashSet<SubmitQuestion>();
		for (SubmitQuestion submitQuestion : set) {
			score += Integer.parseInt(submitQuestion.getScore());
			SubmitQuestion sq  = this.submitQuestionRepository.findById(submitQuestion.getId()).orElse(null);
			sq.setScore(submitQuestion.getScore());
			paperId = (String) this.submitQuestionRepository.findPaper(sq.getId());
			setForIn.add(sq);
			this.submitQuestionRepository.save(sq);
		}
		SubmitPaper sp = this.submitPaperRepository.findById(paperId).orElse(null);
		sp.setIsCorrected("2");
		sp.setQuestions(setForIn);
		sp.setScore(String.valueOf(score));
		return this.submitPaperRepository.save(sp);
	}
	
	public Object findStudentByNoPage()
	{
		List<String> list = this.submitQuestionRepository.findAllAccount();
		List<AccountModel> accountList = new ArrayList<AccountModel>();
		for (String s : list) 
		{
			AccountModel am = this.accountRepository.findById(s).orElse(null);
			if(am != null)
			accountList.add(am);
		}
		return accountList;
	}
}
